package com.example.main.ukey;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class SearchAsyncTask extends AsyncTask<Integer, String, Integer> {

    private static final String TAG = "SearchAsyncTask";

    private OTG_KEY msyUsbKey;
    private Context context;
    byte[] fingerBuf = new byte[ZhiWenUtils.IMAGE_X * ZhiWenUtils.IMAGE_Y];

    public SearchAsyncTask(Context context, OTG_KEY msyUsbKey) {
        this.msyUsbKey = msyUsbKey;
        this.context = context;
    }

    @Override
    protected Integer doInBackground(Integer... integers) {
        int ret;
        int[] fingerId = new int[1];
        while (msyUsbKey.PSGetImage(ZhiWenUtils.DEV_ADDR) == ZhiWenUtils.PS_NO_FINGER) {
        }

        if ((ret = msyUsbKey.PSUpImage(ZhiWenUtils.DEV_ADDR, fingerBuf)) != 0) {
            Log.i(TAG, "上传图像失败:" + ret);
            return -1;
        }
        Log.i(TAG, "上传图像成功");
        if ((ret = ZhiWenUtils.WriteBmp(context, fingerBuf)) != 0) {
            Log.i(TAG, "生成bmp文件失败:" + ret);
            return -1;
        }

        Log.i(TAG, "生成bmp文件成功");

        if (msyUsbKey.PSGenChar(ZhiWenUtils.DEV_ADDR, ZhiWenUtils.CHAR_BUFFER_A) != ZhiWenUtils.PS_OK) {
            Log.i(TAG, "生成特征失败");
            return -1;
        }
        if (ZhiWenUtils.PS_OK != msyUsbKey.PSSearch(ZhiWenUtils.DEV_ADDR, ZhiWenUtils.CHAR_BUFFER_A, 0, 100, fingerId)) {
            Log.i(TAG, "没有找到此指纹");
            return -1;
        }

        Log.i(TAG, "成功搜索到此指纹,ID===>" + fingerId[0]);
        return 0;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.i(TAG, "onPreExecute: 开启搜索指纹");
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        if (integer == 0) {
            Log.i(TAG, "成功搜索到");
        } else {
            Log.i(TAG, "未找奥");
        }
    }
}
